package com.ikingtech.platform.service.oidc.converter;

import com.ikingtech.framework.sdk.utils.Tools;
import com.ikingtech.platform.service.oidc.web.OidcAuthorizationResponse;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 * @author tie yan
 */
@Slf4j
@RequiredArgsConstructor
public class OidcAuthorizationCodeResponseConverter implements OidcResponseConverter {

    @Override
    public void convert(OidcAuthorizationResponse oidcResponse, HttpServletResponse httpResponse) {
        if (Tools.Str.isNotBlank(oidcResponse.getCode())) {
            try {
                String location = oidcResponse.getRedirectUri() + "?" + "code=" + oidcResponse.getCode();
                if (Tools.Str.isNotBlank(oidcResponse.getState())) {
                    location += "&state=" + oidcResponse.getState();
                }
                httpResponse.sendRedirect(location);
            } catch (IOException e) {
                String errorLink = oidcResponse.getRedirectUri() + "?" + "error=server_error&error_description=server error,please try later";
                try {
                    log.error("authorization server send code to {} fail[{}]",  oidcResponse.getRedirectUri(), e.getMessage());
                    httpResponse.sendRedirect(errorLink);
                } catch (IOException e1) {
                    log.error("authorization server redirect to {} fail[{}]",  errorLink, e.getMessage());
                }
            }
        }
    }

    @Override
    public boolean support(OidcAuthorizationResponse oidcResponse) {
        return Tools.Str.isNotBlank(oidcResponse.getCode()) && Tools.Str.isNotBlank(oidcResponse.getRedirectUri());
    }
}
